import { fabric } from 'fabric';

class BaseShape extends fabric.Object {
    constructor(options = {}) {
        super({
            left: 100,
            top: 100,
            fill: '#ffffff',
            strokeWidth: 1,
            stroke: '#000000',
            selectable: true,
            cornerSize: 10,
            transparentCorners: false,
            hasRotatingPoint: true,
            padding: 5,
            id: '', // 添加id属性
            ...options
        });

        // 确保控制点颜色与边框颜色一致
        this.set({
            cornerColor: this.stroke,
            borderColor: this.stroke
        });

        // 如果提供了canvas，自动添加到画布
        if (options.canvas) {
            options.canvas.add(this);
            // 不再手动调用renderAll，使用fabric的自动渲染
        }
    }

    // 更新属性
    updateProps(props) {
        this.set(props);
        // 如果更新了边框颜色，同时更新控制点颜色
        if (props.stroke) {
            this.set({
                cornerColor: props.stroke,
                borderColor: props.stroke
            });
        }
        this.canvas?.requestRenderAll();
        return this;
    }

    // 移到顶层
    bringToFront() {
        if (this.canvas) {
            this.canvas.bringToFront(this);
            this.canvas.requestRenderAll();
        }
        return this;
    }

    // 移到底层
    sendToBack() {
        if (this.canvas) {
            this.canvas.sendToBack(this);
            this.canvas.requestRenderAll();
        }
        return this;
    }

    // 删除自身
    remove() {
        if (this.canvas) {
            this.canvas.remove(this);
            this.canvas.requestRenderAll();
        }
    }

    // 设置大小
    setSize(size) {
        const scale = size / 100; // 基于默认大小100进行缩放
        this.scale(scale);
        this.canvas?.requestRenderAll();
        return this;
    }

    // 安全地绘制控制点
    drawControls(ctx) {
        try {
            if (this.canvas) {
                super.drawControls(ctx);
            }
        } catch (e) {
            console.warn('Error drawing controls:', e);
        }
    }
}

export default BaseShape;
